/**
 * Created by chen on 18/5/22.
 */
var allItems = {list:[{type:"饮料",name:"可口可乐",price:3,unit:"瓶",barcode:"ITEM00001"},
  {type:"饮料",name:"雪碧",price:3,unit:"瓶",barcode:"ITEM00002"},
  {type:"水果",name:"苹果",price:5.5,unit:"斤",barcode:"ITEM00003"},
  {type:"水果",name:"荔枝",price:15,unit:"斤",barcode:"ITEM00004"},
  {type:"生活用品",name:"电池",price:2,unit:"个",barcode:"ITEM00005"},
  {type:"食品",name:"方便面",price:4.5,unit:"袋",barcode:"ITEM00006"}]};

window.onload = function(){
  var tpl = document.getElementById('tpl').innerHTML;
  document.getElementById('shopping_list_info').innerHTML = template(tpl, allItems);
  var allCartList = JSON.parse(localStorage.getItem("cartList"))||[];
  getCartNum(allCartList);
};
function addItemToCart()
{
  var id=$("#"+event.target.id)[0].id;
  var find_item = _.find(allItems.list, function(item){
    return id == item.barcode;
  });

  //保存到本地localstorage
  var allCartList = JSON.parse(localStorage.getItem("cartList"))||[];
  if(allCartList.length == 0)
  {
    find_item.count = 1;
    allCartList.push(find_item);
  }
  else
  {
    var find_item_in_cart = _.find(allCartList,function(item){
      return item.barcode == id;
    });
    if (find_item_in_cart == undefined)
    {
      find_item.count = 1;
      allCartList.push(find_item);
    }else
    {
      find_item_in_cart.count ++
    }
  }
  localStorage.setItem("cartList",JSON.stringify(allCartList));
  //统计购物车数量
  getCartNum(allCartList)

}
